import axios, { AxiosInstance } from "axios";

interface MyAxiosInstance extends AxiosInstance {
  addToken: (token: string) => void;
}

var instance: MyAxiosInstance = axios.create({
  headers: {
    "Content-type": "application/json",
  },
}) as MyAxiosInstance;

//add pre request interceptor
instance.interceptors.request.use((config) => {
  if (instance.defaults.headers.common["Authorization"]) {
    return config;
  }
  const token = localStorage.getItem("token");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

instance.addToken = (token) => {
  localStorage.setItem("token", token);
  instance.defaults.headers.common["Authorization"] = `Bearer ${token}`;
};
